package com.next

import grails.transaction.Transactional
import org.springframework.security.access.annotation.Secured

import static org.springframework.http.HttpStatus.*

@Secured(['ROLE_ADMINISTRATOR', 'ROLE_COMPANY_ADMINISTRATOR', 'ROLE_COMPANY_USER'])
class ActivityTeamController
{
    static allowedMethods = [save: "POST", update: "PUT", delete: "DELETE"]

    def springSecurityService

    def index(Integer max)
    {

        def username = springSecurityService.getPrincipal().username
        def user = User.findByUsername(username)
        def type = ActivityType.findByName('Task')
        String sql = "from ActivityTeam where user.id = ${user.id} and activity.type.id <> ${type.id} order by modifiedDate desc"
        def activityTeamList = ActivityTeam.findAll(sql)
        def count = ActivityTeam.findAll(sql)?.size()

        respond activityTeamList, model: [activityTeamCount: count, params: params]
    }

    def show(ActivityTeam activityTeam)
    {
        respond activityTeam
    }

    def create()
    {
        def activity = Activity.findById(params['activity'])
        def username = springSecurityService.getPrincipal().username
        def user = User.findByUsername(username)
        if (activity?.user == user || UserRole.findByUserAndRole(user, Role.findByAuthority("ROLE_ADMINISTRATOR")))
        {
            def userList = User.list()
            def activityTeams = ActivityTeam.findAllByActivity(activity)
            activityTeams?.each {
                userList -= it?.user
            }
            respond new ActivityTeam(params), model: [userList: userList]
        }
        else
        {
            flash.message = message(code: 'opportunity.edit.permission.denied')
            redirect(controller: "activity", action: "show", params: [id: activity.id])
            return
        }
    }

    @Transactional
    def save(ActivityTeam activityTeam)
    {
        def userList = User.list()
        def activityTeams = ActivityTeam.findAllByActivity(activityTeam?.activity)
        activityTeams?.each {
            userList -= it?.user
        }

        if (activityTeam == null)
        {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        if (activityTeam.hasErrors())
        {
            //COMMENT THE INFO THEN YOU WILL SEE MIRACLES
            log.info "userList:" + userList

            transactionStatus.setRollbackOnly()
            respond activityTeam.errors, model: [userList: userList], view: 'create'
            return
        }

        activityTeam.save flush: true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.created.message', args: [message(code: 'activityTeam.label', default: 'ActivityTeam'), activityTeam.id])
                // redirect activityTeam
                redirect controller: "activity", action: "show", id: activityTeam?.activity?.id
            }
            '*' { respond activityTeam, [status: CREATED] }
        }
    }

    def edit(ActivityTeam activityTeam)
    {
        respond activityTeam
    }

    @Transactional
    def update(ActivityTeam activityTeam)
    {
        if (activityTeam == null)
        {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        if (activityTeam.hasErrors())
        {
            transactionStatus.setRollbackOnly()
            respond activityTeam.errors, view: 'edit'
            return
        }

        activityTeam.save flush: true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.updated.message', args: [message(code: 'activityTeam.label', default: 'ActivityTeam'), activityTeam.id])
                // redirect activityTeam
                redirect controller: "activity", action: "show", id: activityTeam?.activity?.id
            }
            '*' { respond activityTeam, [status: OK] }
        }
    }

    @Transactional
    def delete(ActivityTeam activityTeam)
    {

        if (activityTeam == null)
        {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        activityTeam.delete flush: true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.deleted.message', args: [message(code: 'activityTeam.label', default: 'ActivityTeam'), activityTeam.id])
                redirect action: "index", method: "GET"
            }
            '*' { render status: NO_CONTENT }
        }
    }

    protected void notFound()
    {
        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.not.found.message', args: [message(code: 'activityTeam.label', default: 'ActivityTeam'), params.id])
                redirect action: "index", method: "GET"
            }
            '*' { render status: NOT_FOUND }
        }
    }

    def myTeamTaskList()
    {
        def username = springSecurityService.getPrincipal().username
        def user = User.findByUsername(username)
        def type = ActivityType.findByName('Task')
        String sql = "from ActivityTeam where user.id = ${user.id} and activity.type.id = ${type.id} order by modifiedDate desc"
        def teamTaskList = ActivityTeam.findAll(sql)
        def count = ActivityTeam.findAll(sql)?.size()

        respond teamTaskList, model: [activityTeamCount: count, params: params, teamTaskList: teamTaskList]
    }

    def searchMyTeamTask()
    {
        def username = springSecurityService.getPrincipal().username
        def user = User.findByUsername(username)
        def type = ActivityType.findByName('Task')

        String sql = "from ActivityTeam where user.id = ${user.id} and activity.type.id = ${type.id}"
        def status = params["status"]
        if (status)
        {
            sql += " and activity.status = '${status}'"
        }

        def fullName = params['fullName']
        if (fullName)
        {
            sql += " and activity.assignedTo.fullName like '%${fullName}%'"
        }

        def name = params['name']
        if (name)
        {
            sql += " and activity.name like '%${name}%'"
        }

        sql += " order by modifiedDate desc"

        def teamTaskList = ActivityTeam.findAll(sql)
        def count = ActivityTeam.findAll(sql)?.size()

        respond teamTaskList, model: [activityTeamCount: count, params: params, teamTaskList: teamTaskList], view: 'myTeamTaskList'
    }
}
